package com.baseframe.auth.endpoint;

import com.baseframe.auth.constant.BaseAuthConstant;
import com.baseframe.auth.props.BaseAuthProperties;
import com.baseframe.auth.utils.AuthUtil;
import com.baseframe.auth.utils.TokenUtil;
import com.baseframe.jwt.props.BaseJwtProperties;
import com.baseframe.jwt.utils.JwtUtil;
import com.baseframe.tool.container.Kv;
import com.baseframe.tool.result.R;
import com.baseframe.tool.utils.id.IdType;
import com.baseframe.tool.utils.id.IdUtil;
import com.baseframe.tool.utils.redis.CommonRedisUtil;
import com.wf.captcha.SpecCaptcha;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/oauth")
@AllArgsConstructor
public class BaseTokenEndpoint {

    private BaseJwtProperties baseJwtProperties;

    @GetMapping("/captcha")
    public R<Kv> getCaptcha(){
        SpecCaptcha captcha = new SpecCaptcha(130,40,5);
        String base64Data = captcha.toBase64();//获取图片
        String codeValue = captcha.text();//获取值
        String noLine2UUID = IdUtil.load(IdType.UUID).next();
        //将验证码正确值设置到redis中并设置15分钟过期时间
        CommonRedisUtil.setValue(BaseAuthConstant.CAPTCHA_REDIS_KEY+ noLine2UUID,codeValue,15L, TimeUnit.MINUTES);
        //返回验证码图片和验证码key
        Kv kv = Kv.create();
        kv.setAttribute("key",noLine2UUID);
        kv.setAttribute("image",base64Data);

        return R.data(kv);
    }

    @GetMapping("/logout")
    public R<Object> logout(){

        Boolean single = baseJwtProperties.getSingle();
        Object redisKey = null;
        if (single){
            redisKey = AuthUtil.getUserId();
        }else {
            redisKey = AuthUtil.getJwtKey();
        }

        return TokenUtil.deleteToken(redisKey)?R.success():R.fail();
    }

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @GetMapping("/sms/send")
    public R<Kv> sndSms(String phone){


        return null;
    }

}
